<template>
  <div class="banner-slider" ref="slider" @touchstart.stop="handleTouchStart" @touchmove.stop="handleTouchMove"
    @touchend.stop="handleTouchEnd">
    <!-- 轮播图容器 -->
    <div class="banner-container"
      :style="{ transform: `translateX(-${currentIndex * 100}%)`, transition: isDragging ? 'none' : 'transform 0.3s ease' }">
      <div v-for="(item, index) in bannerList" :key="index" class="banner-item">
        <img :src="item.imgUrl" :alt="item.title" class="banner-img" />
      </div>
    </div>
    <!-- 指示器 -->
    <div class="dots">
      <span v-for="(item, index) in bannerList" :key="index" class="dot"
        :class="{ active: index === currentIndex }"></span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BannerSlider',
  props: {
    bannerList: {
      type: Array,
      default: () => []
    },
    threshold: { // 滑动触发切换的阈值（px）
      type: Number,
      default: 50
    }
  },
  data() {
    return {
      currentIndex: 0,
      startX: 0,    // 触摸起始X坐标
      moveX: 0,     // 触摸移动X坐标
      isDragging: false // 是否正在拖拽
    }
  },
  methods: {
    handleTouchStart(e) {
      this.isDragging = true;
      this.startX = e.touches[0].clientX; // 记录触摸起始位置
    },
    handleTouchMove(e) {
      if (!this.isDragging) return;
      this.moveX = e.touches[0].clientX; // 记录触摸移动位置
    },
    handleTouchEnd() {
      if (!this.isDragging) return;

      const distance = this.moveX - this.startX; // 计算滑动距离
      const bannerLength = this.bannerList.length;

      // 右滑（切换上一张）
      if (distance > this.threshold && this.currentIndex > 0) {
        this.currentIndex--;
      }
      // 左滑（切换下一张）
      else if (distance < -this.threshold && this.currentIndex < bannerLength - 1) {
        this.currentIndex++;
      }

      this.isDragging = false;
      this.startX = 0;
      this.moveX = 0;
    },
    // 自动轮播（可选）
    startAutoPlay() {
      this.timer = setInterval(() => {
        this.currentIndex = (this.currentIndex + 1) % this.bannerList.length;
      }, 3000);
    },
    stopAutoPlay() {
      clearInterval(this.timer);
    }
  },
  mounted() {
    // 可选：自动轮播（移动端一般不需要，可注释）
    // this.startAutoPlay();
  },
  beforeDestroy() {
    // 清理定时器
    this.stopAutoPlay();
  }
}
</script>

<style scoped>
.banner-slider {
  width: 100%;
  overflow: hidden;
  position: relative;
}

.banner-container {
  display: flex;
  width: 100%;
}

.banner-item {
  width: 100%;
  flex-shrink: 0;
}

.banner-img {
  width: 100%;
  height: auto;
}

.dots {
  display: flex;
  justify-content: center;
  position: absolute;
  bottom: 10px;
  left: 0;
  right: 0;
}

.dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.6);
  margin: 0 4px;
}

.dot.active {
  background-color: #ffffff;
}
</style>